package com.baidu.customview.widget;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;

/**
 * Created by imagine on 2015/11/10.
 */
public class MeasureView extends View {
    private Paint paint;

    public MeasureView(Context context) {
        super(context);
        init();
    }

    private void init() {
        paint = new Paint();
        paint.setColor(Color.BLUE);
        paint.setStrokeMiter(300);
    }

    public MeasureView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();

    }

    public MeasureView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public MeasureView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(getWidth(widthMeasureSpec), getHeight(heightMeasureSpec));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        canvas.drawRect(10, 10, 200, 200, paint);
    }

    private int getWidth(int widthMeasureSpec) {
        int width = 0;
        int x = (int) paint.getStrokeWidth();
        int specMode = MeasureSpec.getMode(widthMeasureSpec);
        int specSize = MeasureSpec.getSize(widthMeasureSpec);
        if (specMode == MeasureSpec.AT_MOST) {
            width = x > specSize ? specSize : x;
        } else if (specMode == MeasureSpec.EXACTLY) {
            width = specSize;
        }
        return width;
    }

    private int getHeight(int heightMeasureSpec) {
        int height = 0;
        int y = (int) paint.getStrokeWidth();
        int specMode = MeasureSpec.getMode(heightMeasureSpec);
        int specSize = MeasureSpec.getSize(heightMeasureSpec);
        if (specMode == MeasureSpec.AT_MOST) {
            height = y > specSize ? specSize : y;
        } else if (specMode == MeasureSpec.EXACTLY) {
            height = specSize;
        }
        return height;
    }
}
